﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Web;

namespace BSU.CSCE.Utilities
{
    public static class UriUtil
    {
        public static NameValueCollection AddParamToQueryString(NameValueCollection queryString, string paramKey, string paramValue)
        {
            if (String.IsNullOrEmpty(paramKey))
            {
                throw new ArgumentNullException("paramKey", "paramKey cannot be null or empty");
            }
            if (String.IsNullOrEmpty(paramValue))
            {
                throw new ArgumentNullException("paramValue", "paramValue cannot be null or empty");
            }
            NameValueCollection newQueryString = new NameValueCollection(queryString);
            newQueryString[paramKey] = paramValue;
            return newQueryString;
        }

        public static NameValueCollection RemoveParamFromQueryString(NameValueCollection queryString, string paramKey)
        {
            if (String.IsNullOrEmpty(paramKey))
            {
                throw new ArgumentNullException("paramKey", "paramKey cannot be null or empty");
            }

            NameValueCollection newQueryString = new NameValueCollection(queryString);

            newQueryString.Remove(paramKey);

            return newQueryString;
        }

        public static string ToQueryString(this NameValueCollection queryString)
        {
            var builder = new StringBuilder();

            foreach (string key in queryString.Keys)
            {
                foreach (var value in queryString.GetValues(key))
                {
                    builder.AppendFormat("&amp;{0}={1}", key, HttpUtility.UrlEncode(value));
                }
            }
            if (builder.Length > 0)
            {
                builder.Remove(0, 5).Insert(0, '?');
            }

            return builder.ToString();
        }
    }
}
